package com.itheima.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/resp")
public class ResponseDataServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("resp  execute");

        //向前端响应
       // resp.getWriter().write("ok");
        User u=new User();
        u.setId("3");
        u.setUsername("貂蝉");
        u.setPwd("666");
        //将u转换成json格式的字符串：{"id":"3"...}
        ObjectMapper obj=new ObjectMapper();
        String jsonStr = obj.writeValueAsString(u);

        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(jsonStr);//字符串
    }
}
